<script setup lang="ts">
  import { ref, watch } from 'vue';

  const emits = defineEmits<{
    (e: 'change', item: any, index: number): void;
  }>();

  const props = withDefaults(
    defineProps<{
      data: any[];
      checkFirst?: boolean;
      labelProp?: string;
    }>(),
    {
      checkFirst: true,
      labelProp: 'name',
    }
  );

  const checkIndex = ref(-1);

  const onItemCheck = (item: any, index: number) => {
    checkIndex.value = index;
    emits('change', item, index);
  };

  watch(
    () => props.data,
    (newVal) => {
      if (props.checkFirst && newVal.length > 0) {
        onItemCheck(newVal[0], 0);
      }
    },
    {
      immediate: true,
    }
  );
</script>

<template>
  <div class="ls-wrapper gap-2">
    <div
      v-for="(item, index) in data"
      :key="index"
      :class="[
        'ls-item truncate',
        {
          'ls-item-checked': index === checkIndex,
        },
      ]"
      @click="onItemCheck(item, index)"
    >
      <span class="ls-item-title" :title="item[labelProp]">
        {{ item[labelProp] }}
      </span>
    </div>
  </div>
</template>

<style lang="less" scoped>
  .ls-wrapper {
    display: flex;
    flex-direction: column;
    width: 100%;

    .ls-item {
      width: 100%;
      padding: 10px 16px;
      border: 1px solid var(--color-border-2);
      border-radius: 4px;
      cursor: pointer;
    }

    .ls-item:hover,
    .ls-item-checked {
      border-color: rgb(var(--primary-6));
    }

    .ls-item-checked {
      background-color: var(--color-primary-light-1);
    }

    .ls-item:hover .ls-item-title,
    .ls-item-checked .ls-item-title {
      color: rgb(var(--primary-6));
    }
  }
</style>
